package com.zhaiyz.grpcdemo

import com.zhaiyz.grpcdemo.proto.GreetingRequest
import com.zhaiyz.grpcdemo.proto.GreetingResponse
import com.zhaiyz.grpcdemo.proto.GreetingServiceGrpc
import io.grpc.stub.StreamObserver

/**
 * Created by zhaiyz on 2018/1/17.
 */
class GreetingServiceGrpcImpl : GreetingServiceGrpc.GreetingServiceImplBase() {

    override fun greeting(request: GreetingRequest, responseObserver: StreamObserver<GreetingResponse>) {
        val name = if (request.name.isBlank()) "world" else request.name
        val response = GreetingResponse.newBuilder().setMsg("Hello $name!").build()
        responseObserver.onNext(response)
        responseObserver.onCompleted()
    }

    override fun streamGreeting(responseObserver: StreamObserver<GreetingResponse>): StreamObserver<GreetingRequest> {
        return object : StreamObserver<GreetingRequest> {
            val names = mutableListOf<String>()

            override fun onCompleted() {
                val msg = "Hello " + names.joinToString(",")
                responseObserver.onNext(GreetingResponse.newBuilder().setMsg(msg).build())
                responseObserver.onCompleted()
            }

            override fun onError(t: Throwable) {
            }

            override fun onNext(value: GreetingRequest) {
                names.add(value.name)
            }
        }
    }

    override fun greetingStream(request: GreetingRequest, responseObserver: StreamObserver<GreetingResponse>) {
        val name = if (request.name.isBlank()) "world" else request.name
        val response = GreetingResponse.newBuilder().setMsg("Hello $name!").build()
        (0..3).forEach {
            Thread.sleep(1000)
            responseObserver.onNext(response)
        }
        responseObserver.onCompleted()
    }

    override fun streamGreetingStream(responseObserver: StreamObserver<GreetingResponse>): StreamObserver<GreetingRequest> {
        return object : StreamObserver<GreetingRequest> {
            val names = mutableListOf<String>()

            override fun onCompleted() {
                val msg = "Hello " + names.joinToString(",")
                (0..3).forEach {
                    responseObserver.onNext(GreetingResponse.newBuilder().setMsg(msg).build())
                    Thread.sleep(1000)
                }
                responseObserver.onCompleted()
            }

            override fun onError(t: Throwable) {
            }

            override fun onNext(value: GreetingRequest) {
                names.add(value.name)
                responseObserver.onNext(GreetingResponse.newBuilder().setMsg("Hello " + value.name).build())
            }
        }
    }

}